<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.diseatestreport_delete"
                   @click="handleDelete">删 除
        </el-button>

        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          @click="handleExport"
        >
          导 出
        </el-button>
      </template>

      <!-- 地图表单自定义 -->
      <template slot="mapForm">
        <div v-if="showMap">
          <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler">
            <el-input placeholder="关键词查询" v-model="searchWord" style="position:absolute;top:10px;left:10px;width:180px;">
              <template slot="append">
                <el-button icon="el-icon-search" id="citySearch"></el-button>
              </template>
            </el-input>

            <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
            <bm-marker :position="mapPosition" :dragging="true"></bm-marker>
          </baidu-map>
        </div>
      </template>

      <!-- 附件表格自定义 -->
      <template slot="jcbg" slot-scope="scope">
        <div v-if="scope.row['jcbg'] != ''" class="enclosure_div">
          <a :href="downloadHead + scope.row['jcbg']" style="color: #409eff;">
            <i class="el-icon-download" style="color: #409eff;"></i>下载检测报告
          </a>
        </div>
        <div v-else class="enclosure_div" >
            <a>未上传检测报告</a>
        </div>

      </template>

      <!-- 附件表单自定义 -->
      <template slot="jcbgForm">
        <div>
          <el-upload
            action="/api/fileManager/upload/file"
            :headers="SetHeaders"
            :file-list="fjFileList"
            :before-upload="beforeUploadFJ"
            :on-remove="handleRemoveFJ"
            :on-success="uploadFJSuccess"
          >
            <el-button size="small" type="primary">选择文件</el-button>
          </el-upload>
        </div>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/basedata/occupationalhazards/diseatestreport";
  import {mapGetters} from "vuex";
  import {getToken} from "@/util/auth";

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          searchSpan: 8,
          searchLabelWidth:150,
          searchMenuPosition: 'right',
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "职业病危害因素类别",
              prop: "zybwgyslb",
              align: "center",
              row: false,
              search:true,
              type:'select',
              dicUrl: "/api/occupationalHazards/diseadict/listNoPage?dictType=1",
              props: {
                label: "dictVal",
                value: "id"
              },
              cascaderItem:  ['zybwhysmc'],
              rules: [{
                required: true,
                message: "请输入职业病危害因素类别",
                trigger: "blur"
              }]
            },
            {
              label: "职业病危害因素名称",
              prop: "zybwhysmc",
              align: "center",
              row: false,
              search:true,
              type:'select',
              dicUrl: "/api/occupationalHazards/diseadict/listNoPage?dictType=2&parentId={{key}}",
              props: {
                label: "dictVal",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请输入职业病危害因素名称",
                trigger: "blur"
              }]
            },
            {
              label: "检测机构",
              prop: "jcjg",
              align: "center",
              row: false,
              search: true,
              rules: [{
                required: true,
                message: "请输入检测机构",
                trigger: "blur"
              }]
            },
            {
              label: "检测日期",
              prop: "jcrq",
              align: "center",
              type: 'date',
              rules: [{
                required: true,
                message: "请输入检测日期",
                trigger: "blur"
              }],
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd"
            },

            {
              label: "检测结果编号",
              prop: "jcjgbh",
              align: "center",
              row: false,
              rules: [{
                required: true,
                message: "请输入检测结果编号",
                trigger: "blur"
              }]
            },
            {
              label: "下次检测日期",
              prop: "xcjcrq",
              align: "center",
              row: false,
              type: "date",
              rules: [{
                required: true,
                message: "请输入下次检测日期",
                trigger: "blur"
              }],
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd"
            },
            {
              label: "检测结果",
              prop: "jcjg1",
              align: "center",
              row: false,
              hide: true,
              type: "textarea",
              span: 24,
              maxlength: 150,
              rules: [{
                message: "请输入检测结果",
                trigger: "blur"
              }]
            },
            {
              label: '',
              prop: 'map',
              span: 24,
              hide: true,
              formslot: true,
            },
            {
              label: "经度",
              prop: "jd",
              align: "center",
              row: false,
              hide: true,
              addDisplay: true,
              editDisplay: true,
              viewDisplay: true,
              rules: [{
                required: true,
                message: "经度",
                trigger: "blur"
              }]
            },
            {
              label: "纬度",
              prop: "wd",
              align: "center",
              row: false,
              hide: true,
              addDisplay: true,
              editDisplay: true,
              viewDisplay: true,
              rules: [{
                required: true,
                message: "纬度",
                trigger: "blur"
              }]
            },
            {
              label: "检测报告",
              prop: "jcbg",
              align: "center",
              slot: true,
              formslot: true,
              viewDisplay: false,
            },
            {
              label: "企业",
              prop: "bladeDeptId",
              align: "center",
              row: false,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
            },
            {
              label: "创建人",
              prop: "createUser",
              align: "center",
              row: false,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
            },
            {
              label: "创建部门",
              prop: "createDept",
              align: "center",
              row: false,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
            },
            {
              label: "创建时间",
              prop: "createTime",
              align: "center",
              row: false,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
            },
            {
              label: "修改人",
              prop: "updateUser",
              align: "center",
              row: false,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
            },
            {
              label: "修改时间",
              prop: "updateTime",
              align: "center",
              row: false,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
            },
            {
              label: "检测日期",
              prop: "jcrqTime",
              align: "center",
              row: false,
              type: "date",
              search: true,
              hide: true,
              display:false,
              rules: [{
                required: true,
                message: "请输入下次检测日期",
                trigger: "blur"
              }],
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd"
            },
            {
              label: "下次检测日期",
              prop: "xcjcrqTime",
              align: "center",
              row: false,
              type: "date",
              search: true,
              hide: true,
              display:false,
              rules: [{
                required: true,
                message: "请输入下次检测日期",
                trigger: "blur"
              }],
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd"
            },
          ]
        },
        // 附件
        fjFileList: [],
        downloadHead: "/api/fileManager/download/",
        SetHeaders: { "Blade-Auth": getToken() },
        data: [],
        mapPosition: {
          lng: 121.4472540000,
          lat: 31.3236200000
        },
        center: {
          lng: 121.4472540000,
          lat: 31.3236200000
        },
        zoom: 10,
        dragging: false,
        showMap: true,
        searchWord: ""
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.diseatestreport_add, false),
          viewBtn: this.vaildData(this.permission.diseatestreport_view, false),
          delBtn: this.vaildData(this.permission.diseatestreport_delete, false),
          editBtn: this.vaildData(this.permission.diseatestreport_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    watch: {
      // 表单经度
      'form.jd'(val) {
        if (val) {
          this.mapPosition.lng = val / 1
        }
      },

      // 表单纬度
      'form.wd'(val) {
        if (val) {
          this.mapPosition.lat = val / 1
        }
      },
    },
    methods: {

      // 地图处理事件
      handler({BMap, map}) {
        let _this = this;
        map.addEventListener('click', function(e) {
          _this.form.jd = e.point.lng
          _this.form.wd = e.point.lat
        });

        _this.$nextTick(() => {
          document.getElementById('citySearch').addEventListener('click', function() {
            let localSearch = new BMap.LocalSearch(map)
            localSearch.setSearchCompleteCallback(searchResult => {
              let poi = searchResult.getPoi(0)
              if(!poi) {
                return _this.$message.warning('该地址不存在')
              } else {
                _this.center = {
                  lng: poi.point.lng,
                  lat: poi.point.lat
                }
                _this.form.jd = poi.point.lng
                _this.form.wd = poi.point.lat
              }
            });
            localSearch.search(_this.searchWord);
          });
        })
      },

      //导出
      handleExport() {
        this.$confirm("是否导出职业病危害因素信息?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api//occupationalHazards/diseatestreport/export?${this.website.tokenHeader}=${getToken()}`);
        });
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        this.fjFileList = [];
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            console.log(this.form.bladeFiles.fileName)
            if (type === "edit" && this.form.bladeFiles.fileName !== undefined) {
              this.fjFileList.push({
                name: this.form.bladeFiles.fileName,
                response: {
                  code: 200,
                  success: true,
                  msg: "操作成功",
                  data: this.form.bladeFiles
                }
              });
            }
          });
        }
        done();
      },

      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        getList(page.currentPage, page.pageSize, params).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },

      /**
       * 上传附件
       */

      // 上传检测报告前
      beforeUploadFJ(file) {
        var isLimit = this.fjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
        }
        return isLimit;
      },

      // 上传检测报告成功
      uploadFJSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.fjFileList = fileList;
        this.form.jcbg = response.data.id;
      },

      // 删除检测报告
      handleRemoveFJ(file, fileList) {
        this.fjFileList = fileList;
        this.form.jcbg = "";
      }
    }
  };
</script>

<style>
.map {
  width: 100%;
  height: 500px;
}
</style>
